package com.huarun.module.user.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.huarun.common.util.Constant;
import com.huarun.common.util.HttpUtil;
import com.huarun.common.util.TokenUtil;
import com.huarun.module.user.bean.LessessChild;
import com.huarun.module.user.bean.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 用户获取营运平台中租户数据（管理员和子管理员）
 * 
 * @author eva
 *
 */
public class LesseeInfoUtil {

	private static User u;
	private static Logger logger = LoggerFactory.getLogger(LesseeInfoUtil.class);
	/**
	 * 根据项目名称和部门名称 获取租户信息(管理员 和子管理员）
	 * 
	 * @param request
	 * @param json
	 * @return
	 */
	public static String addLesseeChildrenInfo(HttpServletRequest request, String json) {
		long time = System.currentTimeMillis();
		String url = Constant.ADD_LESSEE_CHILDREN_INFO;
		String token = TokenUtil.createToken(url, request, time, null);
		url = url + "?appkey=" + Constant.MANAGE_APPKEY + "&time=" + time + "&token=" + token;
		try {
			logger.info("接口addLesseeChildrenInfo-ADD_LESSEE_CHILDREN_INFO调用#开始时间："+new Date());
			String returnStr = HttpUtil.postGeneralUrl(Constant.BASE_URL + url, "application/json,text/json", json, "UTF-8");
			logger.info("接口addLesseeChildrenInfo-ADD_LESSEE_CHILDREN_INFO调用-结束时间："+new Date());
			return returnStr;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 根据项目名称和部门名称 获取租户信息(管理员 和子管理员）
	 * 
	 * @param request
	 * @param deptName
	 * @param proId
	 * @return
	 */
	public static String getLesseeInfoByDeptName(HttpServletRequest request, String proId, String deptName) {
		long time = System.currentTimeMillis();
		String url = Constant.TENANT_INFO_BY_TEL_AND_DEPTNAME + proId + "/" + deptName;
		String token = TokenUtil.createToken(url, request, time, null);
		url = url + "?appkey=" + Constant.MANAGE_APPKEY + "&time=" + time + "&token=" + token;
		try {
			logger.info("接口getLesseeInfoByDeptName-TENANT_INFO_BY_TEL_AND_DEPTNAME调用#开始时间："+new Date());
			String returnStr = HttpUtil.doGet(Constant.BASE_URL + url);
			logger.info("接口getLesseeInfoByDeptName-TENANT_INFO_BY_TEL_AND_DEPTNAME调用-结束时间："+new Date());
			return returnStr;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	/**
	 * 根据唯一标识删除子管理员
	 * 
	 * @param request
	 * @param rowGuid
	 * @return
	 */
	public static String delLesseeChild(HttpServletRequest request, String rowGuid) {
		long time = System.currentTimeMillis();
		String url = Constant.DEL_LESSEE_CHILDREN + rowGuid;
		String token = TokenUtil.createToken(url, request, time, null);
		url = url + "?appkey=" + Constant.MANAGE_APPKEY + "&time=" + time + "&token=" + token;
		try {
			
			logger.info("接口delLesseeChild-DEL_LESSEE_CHILDREN调用#开始时间："+new Date());
			String returnStr = HttpUtil.doGet(Constant.BASE_URL + url);
			logger.info("接口delLesseeChild-DEL_LESSEE_CHILDREN调用-结束时间："+new Date());
			return returnStr;

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 根据戎光系统中的数据转换为用户对象
	 * @param info
	 * @param phone
	 * @return
	 */
	public static User formartLesseeinfo2(String info, String phone) {

		if (null != info) {
			JSONObject imisObj = JSONObject.parseObject(info);
			JSONObject data = imisObj.getJSONObject("Data");
			System.out.println(data.toString());
			String errorCode = imisObj.getString("ErrorCode");
			if (null != errorCode && "0".equals(errorCode)) {

				JSONArray lesseeInfoArray = data.getJSONArray("LesseeInfo");
				List<Map<String, Object>> lesseeInfoList = JSON.parseObject(lesseeInfoArray.toJSONString(),
						new TypeReference<List<Map<String, Object>>>() {
						});
				if (null != lesseeInfoList && lesseeInfoList.size() > 0) {
					for (int i = 0; i < lesseeInfoList.size(); i++) {
						if (i == 0) {
							Map<String, Object> map = lesseeInfoList.get(i);
							String userName = (String) map.get("UserName");
							String mobile = (String) map.get("TelPhone");
							String deptName = (String) map.get("LesseeName");
							boolean isMainAdmin = (boolean) map.get("IsMainAdmin");
							JSONArray roomInfo = (JSONArray) map.get("RoomInfo");
							StringBuilder complexFloor = new StringBuilder();
							if ((roomInfo != null) && (roomInfo.size() != 0)) {
								for (int j = 0; j < roomInfo.size(); j++) {
									JSONObject jo = (JSONObject) JSON.toJSON(roomInfo.get(i));
									complexFloor.append(jo.getString("FloorName")).append(",");
								}
							}
							complexFloor = new StringBuilder(complexFloor.substring(0, complexFloor.length() - 1));
							String[] split = complexFloor.toString().split(",");
							Set<String> set = new HashSet(Arrays.asList(split));
							String[] arrayResult = set.toArray(new String[0]);
							StringBuilder floor = new StringBuilder();
							for (String string : arrayResult) {
								floor.append(string).append(",");
							}
							floor = new StringBuilder(floor.length() > 0 ? floor.substring(0, floor.length() - 1) : "");
							// 如果是主管理员，那么拉出子管理员的所有信息,并且拉出对应的房间信息
							if (isMainAdmin) {
								u = new User();
								u.setAccountNo(mobile);
								u.setSynId((String) map.get("RowGuid"));
								u.setWxPhone(mobile);
								u.setUserName(userName);
								u.setDeptName(deptName);
								u.setSynMainId((String) map.get("RowGuid"));
//								u.setRegisterDate(new Date());
								u.setAdmin(Constant.MAIN_ADMIN_ROLE);
								u.setFloor(floor.toString());
							} else {
								JSONArray essessChild = (JSONArray) lesseeInfoList.get(i).get("LessessChildData");
								if (null!=essessChild && essessChild.size() > 0) {
									List<LessessChild> list = JSON.parseObject(essessChild.toJSONString(),
											new TypeReference<List<LessessChild>>() {
											});
									User user = new User();
									for (LessessChild lessessChild : list) {
										if (phone.equals(lessessChild.getTelPhone())) {
											String mobilePhone = lessessChild.getTelPhone();
											user.setAccountNo(mobilePhone);
											user.setWxPhone(mobilePhone);
											user.setSynId(lessessChild.getRowGuid());
											user.setUserName(lessessChild.getUserName());
											user.setDeptName(deptName);
//											user.setRegisterDate(new Date());
											user.setSynMainId((String) map.get("RowGuid"));
											user.setAdmin(Constant.SUB_ADMIN_ROLE);
											user.setFloor(floor.toString());
											System.out.println(user.toString());
											return user;
										}
									}
								}
							}
						}
					}
				} else {
					u = null;
				}
			} else {
				u = null;
			}
		}
		return u;
	}

	public static String getTenantInfoByTelAndProId(HttpServletRequest request, String mobile) {
		long time = System.currentTimeMillis();
		String projectId = request.getHeader("projectId");
		// if (null==projectId||"".equals(projectId)) {
		// projectId="1";
		// }
		System.out.println("getTenantInfoByTelAndProId+项目id是===" + projectId);
		String url = Constant.TENANT_INFO_BY_TEL_AND_PROID + projectId + "/" + mobile;

		String token = TokenUtil.createToken(url, request, time, null);
		url = url + "?appkey=" + Constant.MANAGE_APPKEY + "&time=" + time + "&token=" + token;
		try {
			logger.info("接口getTenantInfoByTelAndProId-TENANT_INFO_BY_TEL_AND_PROID调用#开始时间："+new Date());
			String returnStr = HttpUtil.doGet(Constant.BASE_URL + url);
			logger.info("接口getTenantInfoByTelAndProId-TENANT_INFO_BY_TEL_AND_PROID调用-结束时间："+new Date());
			return returnStr;

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		}
		return null;
	}
	
	
	/**
	 * 根据项目ID和租户名称查找数据
	 * @param request
	 * @param deptName
	 * @return
	 */
	public static String getTenantInfoByDeptNameAndProId(HttpServletRequest request, String deptName) {
		long time = System.currentTimeMillis();
		String projectId = request.getHeader("projectId");
		// if (null==projectId||"".equals(projectId)) {
		// projectId="1";
		// }
		System.out.println("项目id是===" + projectId);
		String url = Constant.TENANT_INFO_BY_TEL_AND_DEPTNAME + projectId + "/" + deptName;

		String token = TokenUtil.createToken(url, request, time, null);
		url = url + "?appkey=" + Constant.MANAGE_APPKEY + "&time=" + time + "&token=" + token;
		try {
			logger.info("接口getTenantInfoByDeptNameAndProId-TENANT_INFO_BY_TEL_AND_DEPTNAME调用#开始时间："+new Date());
			String returnStr = HttpUtil.doGet(Constant.BASE_URL + url);
			logger.info("接口getTenantInfoByDeptNameAndProId-TENANT_INFO_BY_TEL_AND_DEPTNAME调用-结束时间："+new Date());
			return returnStr;

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	

	public static void main(String[] args) {

//		HttpServletRequest request = null;
//		String projectId = "a3697350-929a-f808-f97e-c6b9f499059b";
//		long time = System.currentTimeMillis();
//		String url = Constant.TENANT_INFO_BY_TEL_AND_DEPTNAME + projectId + "/" + "微筑_华润";
//		String token = TokenUtil.createToken(url, request, time, null);
//		url = url + "?appkey=" + Constant.MANAGE_APPKEY + "&time=" + time + "&token=" + token;
//		try {
//			String a = HttpUtil.doGet(Constant.BASE_URL + url);
//			System.out.println("A：" + a);
////			User u = formartLesseeinfo2(a, "13790020871");
//			System.out.println(u);
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
      System.out.println(new Date());
	}
}
